package com.rds.benchmark.command;

import com.rds.benchmark.config.ArgvsConfig;
import com.rds.benchmark.connector.Connector;
import com.rds.benchmark.operator.TypeOperator;
import com.rds.benchmark.thread.MainRunThread;
import com.rds.benchmark.thread.StateThread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

public class TestOperators extends CommandOperator {

    private Class<? extends TypeOperator> operatorClazz;
    private String type;

    public TestOperators(Class<? extends TypeOperator> operatorClazz, String type) {
        this.operatorClazz = operatorClazz;
        this.type = type;
    }

    public void runOperator() throws Exception {
        CyclicBarrier startBarrier = Connector.startBarrier;
        int max_threads = ArgvsConfig.threads;
        Integer req = ArgvsConfig.requests;
        init_pxx();

        final TypeOperator[] operators = new TypeOperator[max_threads];
        for (int i = 0; i < max_threads; i++) {
            operators[i] = operatorClazz.getDeclaredConstructor().newInstance();
        }

        Thread[] threads = new Thread[max_threads];

        int[] thread_req = new int[max_threads];
        int avg_req = 0;
        if (req != null) {
            // 计算一下每个线程需要执行多少请求
            int srt_req = req % max_threads;
            if (srt_req == 0) {
                avg_req = req / max_threads;
            } else {
                int tmp_avg = req / max_threads;
                for (int i = 0; i < thread_req.length; i++) {
                    if (i <= srt_req) {
                        thread_req[i] = tmp_avg + 1;
                    } else {
                        thread_req[i] = tmp_avg;
                    }
                }
            }
        }

        startBarrier.reset();

        CountDownLatch latch = new CountDownLatch(max_threads);

//        StateThread state = null;
        // 搞一堆线程出来
        for (int i = 0; i < max_threads; i++) {
            MainRunThread mainRunThread = new MainRunThread(Integer.toString(i));
            mainRunThread.initParameter(operators, type, latch, avg_req, thread_req);
            threads[i] = mainRunThread;

            threads[i].start();

//            if(i == 0){
//                state = new StateThread();
//                state.initParameter(operators,type,latch,"Performance");
//                state.start();
//            }
        }

        //另启一个线程做数据统计和结果输出
        StateThread state = new StateThread();
        state.initParameter(operators,type,latch,"Performance");

        state.start();
        state.join();

    }
}
